package com.example.projectmanagement.controller.study;

import com.example.projectmanagement.model.study.VideoAccessControl;
import com.example.projectmanagement.model.study.Lesson;
import com.example.projectmanagement.model.User;
import com.example.projectmanagement.service.study.VideoAccessControlService;
import com.example.projectmanagement.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/study/video-access")
@CrossOrigin
public class VideoAccessController {
    
    @Autowired
    private VideoAccessControlService videoAccessControlService;
    
    @Autowired
    private UserService userService;
    
    /**
     * 为视频添加学生访问权限（讲师功能）
     */
    @PostMapping("/videos/{videoId}/students/{studentId}")
    public ResponseEntity<VideoAccessControl> addStudentAccess(
            @PathVariable Long videoId,
            @PathVariable Long studentId) {
        
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        // 检查当前用户是否为讲师或管理员
        if (!hasRole("LECTURER") && !hasRole("ADMIN")) {
            return ResponseEntity.status(403).build();
        }
        
        // 这里需要通过服务层获取视频和学生信息
        // 为简单起见，这里先返回成功响应
        VideoAccessControl control = new VideoAccessControl();
        control.setId(1L); // 临时ID
        
        return ResponseEntity.ok(control);
    }
    
    /**
     * 移除学生访问权限（讲师功能）
     */
    @DeleteMapping("/videos/{videoId}/students/{studentId}")
    public ResponseEntity<Void> removeStudentAccess(
            @PathVariable Long videoId,
            @PathVariable Long studentId) {
        
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        // 检查当前用户是否为讲师或管理员
        if (!hasRole("LECTURER") && !hasRole("ADMIN")) {
            return ResponseEntity.status(403).build();
        }
        
        // 实际删除逻辑在这里实现
        return ResponseEntity.ok().build();
    }
    
    /**
     * 获取视频的学生访问权限列表
     */
    @GetMapping("/videos/{videoId}/students")
    public ResponseEntity<List<VideoAccessControl>> getVideoStudentsAccess(@PathVariable Long videoId) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        // 检查当前用户是否为讲师或管理员
        if (!hasRole("LECTURER") && !hasRole("ADMIN")) {
            return ResponseEntity.status(403).build();
        }
        
        // 实际实现应该从数据库查询
        return ResponseEntity.ok(java.util.Collections.emptyList());
    }
    
    /**
     * 检查学生是否有访问权限
     */
    @GetMapping("/videos/{videoId}/students/{studentId}/access")
    public ResponseEntity<Boolean> checkStudentAccess(
            @PathVariable Long videoId,
            @PathVariable Long studentId) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        // 检查当前用户是否为讲师、管理员或学生本人
        if (!hasRole("LECTURER") && !hasRole("ADMIN") && !currentUserId.equals(studentId)) {
            return ResponseEntity.status(403).build();
        }
        
        // 实际实现应该检查数据库
        return ResponseEntity.ok(true);
    }
    
    /**
     * 获取当前认证用户的ID
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            String username = userDetails.getUsername();
            return userService.getUserByUsername(username).map(User::getId).orElse(null);
        }
        return null;
    }
    
    /**
     * 检查用户是否具有指定角色
     */
    private boolean hasRole(String roleName) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            return authentication.getAuthorities().stream()
                    .anyMatch(authority -> authority.getAuthority().equals("ROLE_" + roleName));
        }
        return false;
    }
}